#include "elk_application.h"
#include "internals/elk_browser_app.h"
#include <QTimerEvent>

ElkApplication::ElkApplication(int &argc, char **argv) :
    QApplication(argc, argv)
{
    connect(this, SIGNAL(msgWorkScheduled()),
            this, SLOT(onMsgWorkScheduled()),
            Qt::QueuedConnection);

    delegate_.reset(new ElkBrowserApp(this));
    if (delegate_->Initialize()) {
        timerIdDoMsgWork_ = startTimer(100);
    }
    connect(this, &QCoreApplication::aboutToQuit, [this]() {
        killTimer(timerIdDoMsgWork_);
        timerIdDoMsgWork_ = 0;

        delegate_->ShutDown();
        delegate_.reset();
    });
}

void ElkApplication::onMsgWorkScheduled(ElkApplication::QPrivateSignal)
{
    if (delegate_) {
        delegate_->DoMsgLoopWork();
    }
}

void ElkApplication::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == timerIdDoMsgWork_) {
        emit msgWorkScheduled(QPrivateSignal());
    }
}
